<template>
	
	<view  class="page group-edit">
		<u--form
			labelPosition="left"
			:model="tbForm"
			:rules="rules"
			ref="uForm"
			labelWidth="auto"
		>
			
			<u-form-item
				label="项目名称"
				borderBottom
				ref="item1"
			>
				<u--input
					v-model="tbForm.xiangmumingcheng"
					disabled
				></u--input>
			</u-form-item>
			<u-form-item
				label="招标单位"
				borderBottom
				ref="item1"
			>
				<u--input
					v-model="tbForm.zhaobiaodanwei"
					disabled
				></u--input>
			</u-form-item>
			<u-form-item
				label="投标价格(元)"
				prop="toubiaojiage"
				borderBottom
				ref="item1"
			>
				<u--input
					v-model="tbForm.toubiaojiage"
					type="number"
					placeholder="请输入投标价格(人民币:元)"
				></u--input>
			</u-form-item>
			<u-form-item
				label="投标文件"
				borderBottom
				ref="item1"
				
			>
				<u-upload
					:fileList="fileList"
					@afterRead="afterRead"
					@delete="deletePic"
					:previewFullImage="true"
					accept="file"
					uploadIcon="arrow-upward"
					:maxCount="1"
					uploadText="上传投标文件"
				></u-upload>
				<text style="color: #007AFF;" v-if="fileList.length">{{fileList[0].name}}</text>
			</u-form-item>
			<u-form-item
				label="投标内容"
				borderBottom
				ref="item1"
				labelPosition="top"
			>
				 <view class="editor-box">
				      <sp-editor
					 
				        :toolbar-config="{
				          excludeKeys: ['export','video','direction', 'date', 
						  'lineHeight', 'letterSpacing', 'listCheck','scriptSub',
						  'scriptSuper','undo','redo','direction','link','indentInc','indentDec'],
				          iconSize: '18px'
				        }"
				        @init="initEditor"
						@input="inputOver"
				        @upinImage="upinImage"
						placeholder="请输入招标内容"
				      ></sp-editor>
				    </view>
			</u-form-item>
		</u--form>
		<u-button type="primary" @click="submit()">提交</u-button>
	</view>
</template>

<script>
	import imageUpload from "@/components/image-upload/image-upload.vue"
	import {zhaobiaoxiangmuDetail, gongyingshangUpdate,zaixiantoubiaoAdd} from '@/api/api.js'
	import {toLogin} from '@/libs/login.js';
	import {mapGetters} from 'vuex';
	import {
		HTTP_REQUEST_URL,
		HEADER,
		TOKENNAME,
		HEADERPARAMS
	} from '@/config/app';
	export default {
		computed: mapGetters(['isLogin','userInfo']),
		components: { imageUpload },
		data() {
			return {
				editorIns: null,
				id:'',
				zb:'',
				baseUrl: HTTP_REQUEST_URL,
				tbForm:{
					xiangmumingcheng: '',
					zhaobiaodanwei: '',
					toubiaojiage: '',
					toubiaoneirong: '',
					tbwjName: '',
					toubiaowenjian: ''
					
				},
				gysForm: {
					id: '',
					gongyingshangmingcheng:'',
					fuzeren: '',
					gongyingshangdianhua: '',
					gongyingshangdizhi: '',
					zizhizhengming:'',
					iscom: '',
				},
				rules: {
					'toubiaojiage': {
						type: 'string',
						required: true,
						message: '请输入投标价格',
						trigger: ['blur', 'change']
					},
					

				},
				fileList: []
			}
		},
		onLoad(options){
			if(!options.id){
				this.$u.toast("参数缺失");
				uni.navigateBack();
				return;
			}
			this.id = options.id
			
			if(this.id){
				this.getDetail()
			}
		},
		onReady() {
				//如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
				 	this.$refs.uForm.setRules(this.rules)
			},
		  onShow() {
			var that = this
			if(!this.$store.getters.isLogin){
				toLogin()
			} else {
			
		  
			}
		  },
		methods: {
			isPDFWordExcel(fileName) {
			  // 定义允许的扩展名（小写）
				const allowedExtensions = ['pdf', 'doc', 'docx', 'xls', 'xlsx'];
			 
				// 获取文件的扩展名（小写）
				const fileExtension = this.getFileExtension(fileName).toLowerCase();
			 
				// 检查扩展名是否在允许的列表中
				return allowedExtensions.includes(fileExtension);
			},
			 
			getFileExtension(fileName) {
			    // 查找最后一个点的位置
			        const lastDotIndex = fileName.lastIndexOf('.');
			     
			        // 如果没有点或者点是文件名的第一个字符（即没有扩展名），则返回空字符串
			        if (lastDotIndex === -1 || lastDotIndex === 0) {
			            return '';
			        }
			     
			        // 返回最后一个点之后的部分作为扩展名
			        return fileName.substring(lastDotIndex + 1);
			},
			 
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			
			// 新增图片
			async afterRead(event) {
				console.log(event)
				var name = event.file.name;
				var size = event.file.size;
				if (size > 4194304 ){
				  uni.showToast({
					title: '文件大小不能超过4MB！',
					icon: "none",
					duration: 2000,
					mask: true
				  })
				   return
				}
				 if ( !this.isPDFWordExcel(name)){ 
					  uni.showToast({
						title: '格式必须为pdf,doc,docx,xls,xlsx',
						icon: "none",
						duration: 2000,
						mask: true
					  })
					  
					  return
					}
				
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let  header = HEADER
					if (this.$store.state.app.token) header[TOKENNAME] = this.$store.state.app.token;
					let a = uni.uploadFile({
						url: HTTP_REQUEST_URL + '/file/upload', // 仅为示例，非真实的接口地址
						header: header,
						filePath: url,
						name: 'file',
						formData: {
							user: 'test'
						},
						success: (res) => {
							console.log('res',res)
							console.log(111,res)
							let data = JSON.parse(res.data);
							console.log(222,data)
							setTimeout(() => {
								resolve(data.data.url)
							}, 1000)
						}
					});
				})
			},
			
			/**
			 * 编辑器就绪
			 * @param {Object} editor 编辑器实例，你可以自定义调用editor实例的方法
			 * @tutorial editor组件 https://uniapp.dcloud.net.cn/component/editor.html#editor-%E7%BB%84%E4%BB%B6
			 * @tutorial 相关api https://uniapp.dcloud.net.cn/api/media/editor-context.html
			 */
			initEditor(editor) {
			  this.editorIns = editor // 保存编辑器实例
			  // 保存编辑器实例后，可以在此处获取后端数据，并赋值给编辑器初始化内容
			  this.preRender()
			},
			preRender() {
			  setTimeout(() => {
				// 异步获取后端数据后，初始化编辑器内容
				// this.editorIns.setContents({
				//   html: `<div>&nbsp;&nbsp;猫猫<img src="https://img.yzcdn.cn/vant/cat.jpeg"/></div>`
				// })
			  }, 1000)
			},
			/**
			 * 获取输入内容
			 * @param {Object} e {html,text} 内容的html文本，和text文本
			 */
			inputOver(e) {
			  // 可以在此处获取到编辑器已编辑的内容
			  this.tbForm.toubiaoneirong = e.html
			},
			upinImage(tempFiles, editorCtx) {
				let  header = HEADER
			    if (this.$store.state.app.token) header[TOKENNAME] = this.$store.state.app.token;
				uni.uploadFile({
					url: HTTP_REQUEST_URL + '/file/upload',
					header: header,
					filePath: tempFiles[0].tempFilePath, // 要上传文件资源的路径
					name: 'file',
					success: (res) => {
						console.log(111,res)
						let data = JSON.parse(res.data);
						console.log(222,data)
						if(data.code != 0){
							
						}else{
							console.log('onSuccess')
						  editorCtx.insertImage({
						    src: data.data.url,
						    width: '80%', // 默认不建议铺满宽度100%，预留一点空隙以便用户编辑
						    success: function () {
						      uni.hideLoading()
						    }
						  })
						}
					},
					fail: (err) => {
						console.log(err);
						
					}
				})
			
			
			},
			getDetail(){
				uni.showLoading({
					title: '加载中'
				});
				zhaobiaoxiangmuDetail(this.id).then(res => {
					uni.hideLoading()
					this.zb= res.data;
					this.tbForm.xiangmumingcheng = this.zb.xiangmumingcheng;
					this.tbForm.zhaobiaodanwei = this.zb.zhaobiaodanwei
					// if(this.zb.toubiaowenjian){
					// 	this.fileList[0] = {
					// 		message: ""
					// 		name: this.zb.toubiaowenjian.
					// 		size: 8394
					// 		status: "success"
					// 		time: 1724034087
					// 		type: "file"
					// 		url: "https://qiniu.gybsky.cn/62f881088c5841-20241125161151.xlsx
					// 	}
					// }
				}).catch(err => {
					console.log(11,err)
					that.$u.toast(err.msg)
					uni.hideLoading()
				})
			},
			submit() {
				console.log('this.fileList',this.fileList)
				if(!this.$store.getters.isLogin){
					toLogin()
					return;
				}
				this.$refs.uForm.validate().then(res => {
					this.add()
				}).catch(errors => {
					console.log('errors',errors)
					uni.$u.toast('校验失败')
				})
			},
			onUploadImageBefore(file,callback) {
				
				
				callback(true)
				// return true;
			},
			onUnloadImageSuccess(file, res) {
				console.log("11",HTTP_REQUEST_URL+res.file)
				this.gysForm.zizhizhengming = res.file;

			},
			add() {
				
				this.tbForm.zhaobiaofenlei = this.zb.zhaobiaofenlei;
				this.tbForm.zhaobiaodanwei = this.zb.zhaobiaodanwei;
				this.tbForm.xiangmumingcheng = this.zb.xiangmumingcheng;
				this.tbForm.xiangmubianhao = this.zb.xiangmubianhao;
				this.tbForm.toubiaowenjian = "";
				// this.tbForm.toubiaoneirong = this.zb.xiangmubianhao;
				this.tbForm.lianxidianhua = this.userInfo.lianxidianhua?this.userInfo.lianxidianhua:this.userInfo.gongyingshangdianhua;
				this.tbForm.gongyingshangmingcheng = this.userInfo.gongyingshangmingcheng;
				this.tbForm.fuzeren = this.userInfo.fuzeren;
				this.tbForm.gysid = this.userInfo.id;
				this.tbForm.zbdwid = this.zb.zbdwid;
				
				// 投标文件tbwjName
			    this.tbForm.tbwjName = this.fileList.length? this.fileList[0]['name']: ''
				this.tbForm.toubiaowenjian = this.fileList.length? this.fileList[0]['url']: ''
				zaixiantoubiaoAdd(this.tbForm).then((res) => {
					uni.showToast({
						title: "投标成功",
						icon: 'none'
					});
					
					setTimeout(() => {
					
						uni.navigateBack();
					}, 1000);

				}).catch(err => {
					this.$u.toast(err)
				})
			},
		
		},
		
		
	}
</script>

<style lang="scss" scoped>
	.group-edit {
		padding: 20rpx;

		.group-image {
			width: 200rpx;
			height: 200rpx;
			border: 1px solid #ccc;
			border-radius: 5%;
		}
	}
	
	.avatar-image {
		position: relative;
		overflow: hidden;
		border: 1px solid #ccc;
		vertical-align: bottom;	
	}
	.editor-box{
		padding: 15px;
		border: 1px solid #dcd7d7;
		margin: 10px;
		width: 330px;
	}
	
</style>